package org.example.try_catch_finally;

import org.junit.Test;

import java.io.*;
import java.util.Scanner;

/**
 * try_catch_finally
 */
public class Test01 {

    public static void main(String[] args) {

        System.out.println(f(2)); // 0
    }

    public static int f(int value) {
        try {
            return value * value;
        } finally {
            if (value == 2) {
                return 0; // 返回值可挽回
            }
        }
    }

    /**
     * Java 中类似于InputStream、OutputStream 、Scanner 、PrintWriter等的资源
     * 都需要我们调用close()方法来手动关闭，一般情况下我们都是通过try-catch-finally语句来实现这个需求，如下：
     */
    @Test
    public void tryFinally (){
        //读取文本文件的内容
        Scanner scanner = null;
        try {
            scanner = new Scanner(new File("D://read.txt"));
            while (scanner.hasNext()) {
                System.out.println(scanner.nextLine());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }


    }


    /**
     * 使用 Java 7 之后的 try-with-resources 语句改造上面的代码:
     */
    @Test
    public void tryWithResource () {
        try (Scanner scanner = new Scanner(new File("test.txt"))) {
            while (scanner.hasNext()) {
                System.out.println(scanner.nextLine());
            }
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        }
    }

    /**
     *  当然多个资源需要关闭的时候，使用 try-with-resources 实现起来也非常简单，如果你还是用try-catch-finally可能会带来很多问题。
     *  通过使用分号分隔，可以在try-with-resources块中声明多个资源。
     *
     *
     *
     */
    @Test
    public void tryWithResource02 () {
        try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
             BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
            int b;
            while ((b = bin.read()) != -1) {
                bout.write(b);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
